<template>
    <div>
        <el-tabs v-model="searchForm.tab" @tab-change="getData">
            <el-tab-pane v-for="(item,index) in tabbars" :key="index" :label="item.name" :name="item.key">
            </el-tab-pane>
        </el-tabs>

        <el-card class="border-0">
            <Search :model="searchForm" @search="getData" @reset="resetSearchForm">
                <SearchItem label="关键词">
                    <el-input v-model="searchForm.title" placeholder="商品名称" clearable></el-input>
                </SearchItem>
                <template #show>
                    <SearchItem label="商品分类">
                        <el-select v-model="searchForm.category_id" placeholder="请选择商品分类" clearable>
                            <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id">
                            </el-option>
                        </el-select>
                    </SearchItem>
                </template>
            </Search>

            <!-- 新增|刷新 -->
            <ListHeader layout="create,refresh" @create="handleCreate" @refresh="getData">
                <el-button type="danger" size="small" @click="handleMult" v-if="searchForm.tab !== 'delete'">批量删除</el-button>
                <el-button type="warning" size="small" @click="handleRestoreGoods" v-else>恢复商品</el-button>
                <el-popconfirm v-if="searchForm.tab == 'delete'" title="是否要彻底删除该商品？" confirmButtonText="确认" cancelButtonText="取消" @confirm="handleDeleteDestroy">
                    <template #reference>
                        <el-button type="danger" size="small">彻底删除</el-button>
                    </template>
                </el-popconfirm>
                <el-button size="small" @click="handleMultiStatusChange(1)" v-if="searchForm.tab == 'all' || searchForm.tab == 'off'">上架</el-button>
                <el-button size="small" @click="handleMultiStatusChange(0)" v-if="searchForm.tab == 'all' || searchForm.tab == 'saling'">下架</el-button>
            </ListHeader>

            <el-table :data="tableData" stripe style="width: 100%" v-loading="loading" @selection-change="handleSelectionChange">
                <el-table-column type="selection" />

                <el-table-column label="商品" width="300">
                    <template #default="{ row }">
                        <div class="flex">
                            <el-image :src="row.cover" fit="fill" :lazy="true" style="width:50px;height: 50px;" class="mr-3 rounded"></el-image>
                            <div class="flex-1">
                                <p>{{ row.title }}</p>
                                <div>
                                    <span class="text-rose-500">￥ {{ row.min_price }}</span>
                                    <el-divider direction="vertical"></el-divider>
                                    <span class="text-gray-500 text-xs">￥ {{ row.min_oprice }}</span>
                                </div>
                                <div class="text-gray-500 text-xs">分类: {{ row.category?row.category.name:'未分类' }}</div>
                                <div class="text-gray-500 text-xs">
                                    创建时间：{{ row.create_time }}
                                </div>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="实际销量" width="70" prop="sale_count" align="center" />
                <el-table-column label="商品状态" width="70">
                    <template #default="{ row }">
                        <el-tag :type="row.status == '0' ? 'danger' : 'success'" size="small">
                            {{ row.status == '0' ? '仓库' : '上架' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="审核状态" width="100" align="center" v-if="searchForm.tab !== 'delete'">
                    <template #default="{ row }">
                        <div class="flex flex-col" v-if="row.ischeck == 0">
                            <el-button type="success" size="small" plain @click="handleCheckGoodsStatus(row,1)">审核通过</el-button>
                            <el-button class="mt-2 !ml-0" type="danger" size="small" plain @click="handleCheckGoodsStatus(row,2)">审核拒绝</el-button>
                        </div>
                        <span v-else>
                            {{ row.ischeck == 1 ? '通过' : '拒绝' }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="总库存" width="90" prop="stock" align="center" />
                <el-table-column label="操作" align="center">
                    <template #default="scope">
                        <div v-if="searchForm.tab !== 'delete'">
                            <el-button class="px-1" type="primary" size="small" @click="handleEdit(scope.row)" text>修改</el-button>
                            <el-button class="px-1" :type="(scope.row.sku_type == 0 && !scope.row.sku_value) || (scope.row.sku_type == 1 && !scope.row.goods_skus_length) ? 'danger' : 'primary'" size="small" text @click="handleSetGoodsSkus(scope.row)" :loading="scope.row.skusLoading">商品规格</el-button>
                            <el-button class="px-1" :type="scope.row.goods_banner.length == 0 ?'danger' : 'primary'" size="small" text @click="handleSetGoodsBanners(scope.row)" :loading="scope.row.bannersLoading">设置轮播图</el-button>
                            <el-button class="px-1" :type="!scope.row.content ?'danger' : 'primary'" size="small" text @click="handleSetGoodsContent(scope.row)" :loading="scope.row.contentLoading">商品详情</el-button>
                            <el-popconfirm title="是否要删除该管理员？" confirmButtonText="确认" cancelButtonText="取消" @confirm="handleDelete(scope.row.id)">
                                <template #reference>
                                    <el-button text type="primary" size="small">删除</el-button>
                                </template>
                            </el-popconfirm>
                        </div>
                        <span v-else>暂无操作</span>
                    </template>
                </el-table-column>
            </el-table>

            <div class="flex items-center justify-center mt-5">
                <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage" :page-size="limit" @current-change="getData" />
            </div>

            <FormDrawer destroyOnClose ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit">
                <el-form :model="form" ref="formRef" :rules="rules" label-width="80px" :inline="false">
                    <el-form-item label="商品名称" prop="title">
                        <el-input v-model="form.title" placeholder="请输入商品名称,不能超过60个字符"></el-input>
                    </el-form-item>
                    <el-form-item label="封面" prop="cover">
                        <ChooseImage v-model="form.avatar" />
                    </el-form-item>
                    <el-form-item label="商品分类" prop="category_id">
                        <el-select v-model="form.category_id" placeholder="请选择商品分类" clearable>
                            <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="商品描述" prop="desc">
                        <el-input v-model="form.desc" placeholder="选填:商品买点描述" type="textarea"></el-input>
                    </el-form-item>
                    <el-form-item label="单位" prop="unit" style="width:50%">
                        <el-input v-model="form.unit" placeholder="请选择单位"></el-input>
                    </el-form-item>
                    <el-form-item label="总库存" prop="stock" style="width:70%">
                        <el-input v-model="form.stock">
                            <template #append>
                                件
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="库存预警" prop="min_stock" style="width:70%">
                        <el-input v-model="form.min_stock">
                            <template #append>
                                件
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="最低销售价" prop="min_price" style="width:70%">
                        <el-input v-model="form.min_price">
                            <template #append>
                                件
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="最低原价" prop="min_oprice" style="width:70%">
                        <el-input v-model="form.min_oprice">
                            <template #append>
                                件
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="是否显示" prop="stock_display">
                        <el-radio-group v-model="form.stock_display">
                            <el-radio :label="0" border>隐藏</el-radio>
                            <el-radio :label="1" border>显示</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="是否上架" prop="status">
                        <el-radio-group v-model="form.status">
                            <el-radio :label="0" border>放入仓库</el-radio>
                            <el-radio :label="1" border>立即上架</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>
            </FormDrawer>
        </el-card>

        <Banners ref="bannersRef" @reloadData="getData" />
        <Content ref="contentRef" @reloadData="getData" />
        <Skus ref="skusRef" @reloadData="getData" />
    </div>
</template>
<script setup>
import { ref } from "vue"
import Banners from './banners.vue'
import Content from './content.vue'
import Skus from './skus.vue'
import Search from '~/components/Search.vue'
import SearchItem from "~/components/SearchItem.vue";
import FormDrawer from "~/components/FormDrawer.vue";
import ChooseImage from "~/components/ChooseImage.vue";
import ListHeader from "~/components/ListHeader.vue";
import {
    getGoodsList,
    updateGoodsStatus,
    createGoods,
    updateGoods,
    deleteGoods,
    restoreGoods,
    destroyGoods,
    checkGoodsStatus
} from "~/api/goods"
import { toast } from '~/composables/util.js'
import { getCategoryList } from '~/api/category.js'
import { useInitTable, useInitForm } from "~/composables/useCommon";
const { searchForm,
    resetSearchForm,
    tableData,
    loading,
    currentPage,
    total,
    limit,
    getData,
    handleDelete,
    handleSelectionChange,
    handleMult,
    handleMultiStatusChange,
    multiSelectionIds,
    multipleTableRef } = useInitTable({
        searchForm: {
            title: '',
            tab: 'all',
            category_id: null
        },
        getList: getGoodsList,
        delete: deleteGoods,
        updateStatus: updateGoodsStatus,
        onGetListSuccess: (res) => {
            tableData.value = res.list.map((o) => {
                o.bannersLoading = false
                o.contentLoading = false
                o.skusLoading = false
                return o
            })
            total.value = res.totalCount
        }
    })

const { formDrawerRef,
    formRef,
    form,
    rules,
    drawerTitle,
    handleSubmit,
    handleCreate,
    handleEdit } = useInitForm(
        {
            form: {
                title: null, //商品名称
                category_id: null, //商品分类
                cover: null, //商品封面
                desc: null, //商品描述
                unit: "件", //商品单位
                stock: 100, //总库存
                min_stock: 10, //库存预警
                status: 0, //是否上架 0仓库1上架
                stock_display: 0, //库存显示 0隐藏1禁用
                min_price: 0, //最低销售价
                min_oprice: 0, //最低原价
            },
            getData,
            update: updateGoods,
            create: createGoods
        })

// 定义标签
const tabbars = [
    {
        key: 'all',
        name: '全部'
    },
    {
        key: 'checking',
        name: '审核中'
    }, {
        key: 'saling',
        name: '出售中'
    }, {
        key: 'off',
        name: '已下架'
    }, {
        key: 'min_stock',
        name: '库存预警'
    }, {
        key: 'delete',
        name: '回收站'
    }
]


// 商品分类
const categoryList = ref([])
getCategoryList().then(res => {
    categoryList.value = res
})

// 展开和收起的切换
const showSearch = ref(false)


// 设置轮播图相关的参数
const bannersRef = ref(null)
// 打开轮播图的方法
const handleSetGoodsBanners = (row) => {
    bannersRef.value.open(row)
}

// 设置轮播图相关的参数
const contentRef = ref(null)
// 打开轮播图的方法
const handleSetGoodsContent = (row) => {
    contentRef.value.open(row)
}

// 设置轮播图相关的参数
const skusRef = ref(null)
// 打开轮播图的方法
const handleSetGoodsSkus = (row) => {
    skusRef.value.open(row)
}

// 恢复商品的方法
const handleRestoreGoods = () => {
    loading.value = true

    restoreGoods(multiSelectionIds.value).then(res => {
        toast('恢复成功')
        getData()
    }).finally(() => {
        loading.value = false
    })
}

// 彻底删除商品
const handleDeleteDestroy = () => {
    loading.value = true
    destroyGoods(multiSelectionIds.value).then(res => {
        toast('彻底删除成功')
        getData()
    }).finally(() => {
        loading.value = false
    })
}

const handleCheckGoodsStatus = (row, status) => {
    loading.value = true
    checkGoodsStatus(row.id, {
        ischeck: status
    }).then(res => {
        toast(`操作成功`)
        getData()
    }).finally(() => {
        loading.value = false
    })
}
</script>